<?php
class myezclass {

	public $link;
	public $webset;
	
	public $dbserver;
	public $dbuser;
	public $dbpass;
	public $dbname;
	public $TABLEPRE;
	public $sql_log=0;
	public $lastsql;
    public $errorData;
	
	function connect(){
        //var_dump($this->dbserver, $this->dbuser, $this->dbpass);
	    $this->link = mysql_connect($this->dbserver, $this->dbuser, $this->dbpass);
		if(!$this->link){echo '数据库连接失败！';exit;}
		$query=$this->select_db($this->dbname);
		if($query!=1){
			$sql = "CREATE DATABASE IF NOT EXISTS `".$this->dbname."` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
			$query=$this->query($sql);
			if($query==''){
				ez_exit('没有创建数据库的权限');
			}
			$this->select_db($this->dbname);
		}
		$this->query("set names utf8");
		return $this->link;
	}
	
	function select_db($dbname){
	    return mysql_select_db($dbname,$this->link);
	}
	
	function ping(){
	    if(mysql_ping()==''){
		    $this->close();
			$this->connect();
		}
	}
	
	function close(){
	    mysql_close($this->link);
	}

	function query($sql,$alert=0) {
		$this->lastsql = $sql;
		if($alert==1){
			echo $sql;
		}
		if($this->webset['sql_log']==1 || $this->sql_log==1){
			//$str=$sql.'-----'.get_client_ip().'-----'.date('H:i:s')."\r\n";
		//	$filename=EZROOT.'/data/temp/sql/'.date('Ym').'/'.date('d').'_'.md5(EZKEY).'.log';
		//	create_file($filename,$str,1,1);
		}
		if(defined('ADMIN')){
			//$str=get_client_ip().'-----'.$sql.'-----'.date('H:i:s')."\r\n";
			//$filename=EZROOT.'/data/temp/admin_sql/'.date('Ym').'/'.date('d').'_'.md5(EZKEY).'.log';
			//create_file($filename,$str,1,1);
		}
		$query=mysql_query($sql,$this->link);
		if($query==''){
			if($this->webset['sql_debug']==1){
				//$filename=EZROOT.'/data/temp/error_sql/'.date('Ym').'/'.date('d').'_'.md5(EZKEY).'.log';
				//create_file($filename,$this->error().'---'.$sql."\r\n",1,1);
				//echo $this->error().'<br/>'.$sql;exit;
			}
            echo $this->error().'<br/>'.$sql;exit;
		}
		else{
			return $query;
		}
	}

	function fetch_array($query, $result_type = MYSQL_ASSOC) {
		return mysql_fetch_array($query, $result_type);
	}
	
	function num_rows($query){
	    return mysql_num_rows($query);
	}
	
	function insert_id(){
	    return mysql_insert_id($this->link);
	}
	
	function free_result(&$query){
		$re=mysql_free_result($query);
		/*if($re!=1){
		    print_r(debug_backtrace());
			exit;
		}*/
	}
	
	function real_escape_string($var){
		return $var=mysql_real_escape_string($var);
	}

	function error() {
		return mysql_error();
	}
	
	function get_version($isformat = true) {
	    $rs = $this->query("SELECT VERSION();");
	    $row = $this->fetch_array($rs,MYSQL_NUM);
	    $mysql_version = $row[0];
	    $this->free_result($rs);
	    if ($isformat) {
		    $mysql_versions = explode(".", trim($mysql_version));
		    $mysql_version = number_format($mysql_versions[0] . "." . $mysql_versions[1], 2);
	    }
	    return $mysql_version;
    }
	
	function show_index($table){
		$query = $this->query("SHOW INDEX FROM ".TABLEPRE.$table);
		if($query!=''){
			while ($arr = $this->fetch_array($query)) {
				$index_info[] = $arr['Column_name'];
			}
		}
		return $index_info;
	}
	
	public function con($a) {
		if(!is_array($a)) return $a;
		$where = '';
		$temp=array();
		$i = 0;
		if(!is_array($a[0])){
		    foreach($a as $k=>$v){
    	        $temp[]=$k."='".$v."'";
            }
			$where='where '.implode(' and ',$temp);
		}
		else{
		    foreach ($a as $row) {
			    if ($i == 0) {
				    $where .= ' where ';
			    } else {
				    if ($row['c'] == '') {
					    $where .= ' and ';
				    } else {
					    $where .= ' ' . $row['c'] . ' ';
				    }

			    }
			    if ($row['e'] == '') {
				    $row['e'] = '=';
			    }
			    $where .= $row['f'] . ' ' . $row['e'] . ' "' . $row['v'] . '"';
			    $i++;
		    }
		}
		return $where;
	}
	function check_token($token){
		    $id=$this->select('user_token','*',"token='$token'");
		    if(!empty($id)) return $id;
		    else return 0;
	}	
	function get_query_conditions($query_item){
        foreach($query_item as $row){
			if($row['f']!=''){
			    if($row['v']!=='' && $row['v']!=='%%'){
					if(isset($row['equal']) && $row['equal']=='in'){
					    $str1[] = $row['f']." ".$row['e']." ".$row['v'];
					}
					else{
					    $str1[] = $row['f']." ".$row['e']." '".$row['v']."'";
					}
			    }
			}
			else{
			    foreach($row as $arr){
				    if($arr['v']!=='' && $arr['v']!=='%%'){
						if($arr['e']=='in'){
						    $str2[] = $arr['f']." ".$arr['e']." ".$arr['v'];
						}
						else{
						    $str2[] = $arr['f']." ".$arr['e']." '".$arr['v']."'";
						}
			        }
				}
				if($str2[1]!=''){
					$str3='('.implode(' or ',$str2).')';
				}
				elseif($str2[1]=='' && $str2[0]!=''){
				    $str3=$str2[0];
				}
				else{
				    $str3='';
				}
			}
			
        }
		if(isset($str3) && $str3!='') $str1[]=$str3;
		if($str1[1]!=''){
			return implode(' and ',$str1);
		}
		elseif($str1[1]=='' && $str1[0]!=''){
			return $str1[0];
		}
		else{
			 return '1=1';
		}
    }
   	function get_cat_level($parentid,$level=0,$tabname="category"){
        if($parentid==0){
       	        return $level;
        }
        $catrow=$this->select($tabname,"parentid,level","id=".$parentid."");
        if(empty($catrow)){
           return $level; 
        }
       
        $level++;
        if($catrow["parentid"]==0){
            return $level;
        }else{
            $level=$this->get_cat_level($catrow["parentid"],$level,$tabname);
            return $level;
        }
          
           
    }
    function get_cattree2($parentid=0,$tabname="category"){
	   global $catlist;
	   $catrow=$this->select_all($tabname,"id,name,parentid,level"," parentid=".$parentid." order by displayorder asc");
       $row=array();
       if(!empty($catrow)){
        $f="";
        while(list($k,$v)=each($catrow)){
            $catid=$v["id"];
            $catname=$v["name"]; 
            $row[$catid]=$v;
            
            $row[$catid]["child"]=$childlist;
            $f="";
            if($v["level"]==1){
                $f="&nbsp;";
            }elseif($v["level"]==2){
                $f="&nbsp;&nbsp;";
            }elseif($v["level"]==3){
                $f="&nbsp;&nbsp;&nbsp;";
            }elseif($v["level"]==4){
                $f="&nbsp;&nbsp;&nbsp;&nbsp;";
    
            }
            
            if($f<>""){
                $catlist[$catid]=$f."├ ".$catname;    
            }else{
                $catlist[$catid]=$catname;
            }
            $childlist=$this->get_cattree2($catid,$tabname);
        }
        if($f<>""){
            $catlist[$catid]=$f."└ ".$catname;
        }
       }
      return $row; 
	}

        /*查询名厨(名店列表)*/
        function get_chefbyid($tabname="shopping3_chef"){
            $chef=$this->select_all($tabname,"id,name");
            return $chef;
        }
        /*根据id查询名厨名称(名店列表)*/
        function get_namebyid($tabname="shopping3_chef",$where){
            $shop_name=$this->select_1_field($tabname,"name",$where);
            return $shop_name[0];
        }
        /*根据优惠券id查询优惠券名称*/
        function get_namebycouponid($tabname="card_coupon",$where){
            $name=$this->select_1_field($tabname,"title",$where);
            return $name[0];
        }
        /*获取菜系数组*/
        function getcuisinelist(){
            $cuisinelist=array(
            '0'=>array('name'=>'请选择','img'=>''),
            '1'=>array('name'=>'鲁菜','img'=>''),
            '2'=>array('name'=>'粤菜','img'=>'images/yue.png'),
            '3'=>array('name'=>'川菜','img'=>'images/chuan.png'),
            '4'=>array('name'=>'湘菜','img'=>''),
            '5'=>array('name'=>'闽菜','img'=>''),
            '6'=>array('name'=>'浙菜','img'=>''),
            '7'=>array('name'=>'苏菜','img'=>''),
            '8'=>array('name'=>'徽菜','img'=>'images/hui.png'),
           );
            return $cuisinelist;
        }
	function get_cattree($parentid=0,$tabname="category"){
	   global $catlist;
	   $catrow=$this->select_all($tabname,"id,catname,parentid,level"," parentid=".$parentid." order by listorder asc");
       $row=array();
       if(!empty($catrow)){
        $f="";
        while(list($k,$v)=each($catrow)){
            $catid=$v["id"];
            $catname=$v["catname"]; 
            $row[$catid]=$v;
            
            $row[$catid]["child"]=$childlist;
            $f="";
            if($v["level"]==1){
                $f="&nbsp;";
            }elseif($v["level"]==2){
                $f="&nbsp;&nbsp;";
            }elseif($v["level"]==3){
                $f="&nbsp;&nbsp;&nbsp;";
            }elseif($v["level"]==4){
                $f="&nbsp;&nbsp;&nbsp;&nbsp;";
    
            }
            
            if($f<>""){
                $catlist[$catid]=$f."├ ".$catname;    
            }else{
                $catlist[$catid]=$catname;
            }
            $childlist=$this->get_cattree($catid,$tabname);
        }
        if($f<>""){
            $catlist[$catid]=$f."└ ".$catname;
        }
       }
      return $row; 
	}
	function sql_to_array($sql){
		$query=$this->query($sql);
		while ($row = $this->fetch_array($query)) {
			$arr[]=$row;
		}
		//if(!isset($arr[1])){$arr=$arr[0];}
		$this->free_result($query);
		return $arr;
	}
	
	function select2arr($sql,$x=0) {
	   
		$query = $this->query($sql);
		while ($row = $this->fetch_array($query)) {
			$arr[] = $row;
		}
		if($x==0){
		    $re = $arr;
		}
		else{
		    $re = $arr[0];
		}
		$this->free_result($query);
		if(!is_array($re)){$re=array();}
		return $re;
	}

	function select($table, $sel_field, $where='1', $alert = 0) {
		$arr='';

		if(strstr($table,',')!=''){
		    $table=str_replace(',',','.$this->TABLEPRE,$table);
		}
		$sql = "select $sel_field from " . $this->TABLEPRE . $table . " where $where limit 1";
		if ($alert == 1) {
			echo $sql;
		}
        
		$query = $this->query($sql);
		if ($query!='') {
			while ($row = $this->fetch_array($query)) {
				if(strpos($sel_field, ",")!==false or strpos($sel_field, "*")!==false) {
					$arr = $row;
				} 
				else{
					$arr = array_pop($row);
				}
			}
			$this->free_result($query);
		}
		return $arr;
	}
	
	function select_all($table, $sel_field, $where='1=1', $alert = 0) {
		$arr = array ();
		if(strstr($table,',')!=''){
		    $table=str_replace(',',','.$this->TABLEPRE,$table);
		}
		$sql = "select $sel_field from ".$this->TABLEPRE.$table." where $where ";
		if ($alert == 1) {
			echo $sql;
		}
		$query = $this->query($sql);
		if ($query!='') {
			while ($row = $this->fetch_array($query)) {
				$arr[] = $row;
			}
			$this->free_result($query);
		}
		return $arr;
	}
	
	function select_all_key($table, $sel_field, $where='1=1', $key='id', $alert = 0) {
		$arr = array ();
		if(strstr($table,',')!=''){
		    $table=str_replace(',',','.$this->TABLEPRE,$table);
		}
		$sql = "select $sel_field from ".$this->TABLEPRE.$table." where $where ";
		if ($alert == 1) {
			echo $sql;
		}
		$query = $this->query($sql);
		if ($query!='') {
			while ($row = $this->fetch_array($query)) {
				$arr[$row[$key]] = $row;
			}
			$this->free_result($query);
		}
		return $arr;
	}
	
	function select_1_field($table, $sel_field='title', $where='1=1', $alert = 0) { //1个字段，输出一维数组
		$sql = "select $sel_field from ".$this->TABLEPRE.$table." where $where ";
		if ($alert == 1) {
			echo $sql;
		}
		$query = $this->query($sql);
		if ($query!='') {
			while ($row = $this->fetch_array($query,MYSQL_NUM)) {
				$arr[] = $row[0];
			}
			$this->free_result($query);
		}
		return $arr;
	}
	
	function select_2_field($table, $sel_field='id,title', $where='1=1', $alert = 0) { //2个字段，输出一维数组，第一个字段是键名，第二个字段是键值
		$sql = "select $sel_field from ".$this->TABLEPRE.$table." where $where ";
		if ($alert == 1) {
			echo $sql;
		}
		$query = $this->query($sql);
		if ($query!='') {
			while ($row = $this->fetch_array($query,MYSQL_NUM)) {
				$arr[$row[0]] = $row[1];
			}
			$this->free_result($query);
		}
		return $arr;
	}
	
	function select_3_field($table, $sel_field='id,title,content', $where='1=1', $alert = 0) { //3个字段，输出二维数组，第一个字段是键名，第二，三组成数字作为子数组
		$field_arr=explode(',',$sel_field);
		$sql = "select $sel_field from ".$this->TABLEPRE.$table." where $where ";
		if ($alert == 1) {
			echo $sql;
		}
		$query = $this->query($sql);
		if ($query!='') {
			while ($row = $this->fetch_array($query)) {
				$arr[$row[$field_arr[0]]] = array($field_arr[1]=>$row[$field_arr[1]],$field_arr[2]=>$row[$field_arr[2]]);
			}
			$this->free_result($query);
		}
		return $arr;
	}
	
    function update($table, $set_con_arr, $where,$limit=0,$alert = 0) {
		$set = '';
	    if (!array_key_exists(0,$set_con_arr)) {
		    $set_arr[0] = $set_con_arr;
	    } else {
		    $set_arr = $set_con_arr;


	    }

	    if(!array_key_exists('f',$set_arr[0])){
            foreach ($set_arr[0] as $k => $v) {

            	$set = "`$k`='$v'," . $set;
            }
			$set = substr($set, 0, strlen($set) - 1);
	    }
        else{
        	foreach ($set_arr as $k => $v) {
		        if (!isset($v['e']) || $v['e'] == '' || $v['e']=='=') {
			        $temp[] = "`" . $v['f'] . "`='" . $v['v'] . "'";
		        } else {
			        $temp[] = "`" . $v['f'] . "`=`" . $v['f'] . "`" . $v['e'] . "'" . $v['v'] . "'";
		        }
	        }
	        $set = implode(',', $temp);
        }
	    if($limit==0){
			$limit='';
		}
		elseif($limit>0){
			$limit=' limit '.$limit;
		}
	    $sql = "update " . $this->TABLEPRE . $table . " set " . $set . " where " . $where . $limit;
        //echo $sql;
		if ($alert == 0) {
			$this->query($sql);
			return $set_arr;
		}
		elseif ($alert == 1) {
		  echo $sql;
			$this->query($sql);
			
		}
	}
	
	function update_serialize($field,$key,$value,$alert=0){
	    $str=$this->select('webset','val','var="'.$field.'"');
		$row=unserialize($str);
		$row[$key]=$value;
		$data=array('val'=>serialize($row));
		$this->update('webset',$data,'var="'.$field.'"');
	}
	
	function insert($table, $field_arr, $alert = 0) {
		$field = "";
		$values = "";
		foreach ($field_arr as $k => $v) {
			$field = "`" . $k . "`," . $field;
			$values = "'" . $v . "'," . $values;
		}
		$field = substr($field, 0, strlen($field) - 1);
		$values = substr($values, 0, strlen($values) - 1);
		$sql = 'insert into '.$this->TABLEPRE.$table.'('.$field.') values ('.$values.');';
		$query = $this->query($sql);
		if ($query!=''){
			$re = $this->insert_id();
		}
	    else{
			$re = -1;
		}
		if ($alert == 1) {
			echo $sql . "<br/>";
		}
		return $re;
	}
	
	function get_table_struct($tablename){
		$table_struct=array();
		$query = $this->query('show fields from `' . TABLEPRE . $tablename.'`');
		if($query==''){return 0;}
		while ($arr = $this->fetch_array($query)) {
			$info = $arr['Type'];
			if ($arr['Null'] == 'NO') {
				$info .= ' NOT NULL';
			}
			$type = strtolower(preg_replace('/\((.*)\)/', '', $arr['Type']));
			if ($type == 'int' or $type == 'tinyint' or $type == 'bigint' or $type == 'double') { //数字类型<br>
				if ($arr['Default'] != '') {
					$info .= ' default "' . $arr['Default'] . '"';
				}
			} else {
				if ($arr['Null'] == 'YES') {
					if ($arr['Default'] != '') {
						$info .= ' default "' . $arr['Default'] . '"';
					} else {
						$info .= ' default NULL';
					}
				}
			}

			if ($arr['Extra'] != '') {
				$info .= ' ' . $arr['Extra'];
			}

			$table_struct[$arr['Field']] = $info;

			if ($arr['Key'] != '') {
				if ($arr['Key'] == 'PRI') {
					$table_index = 'PRIMARY KEY  (`' . $arr['Field'] . '`)';
				}
				elseif ($arr['Key'] == 'UNI') {
					$table_index .= ',UNIQUE KEY `' . $arr['Field'] . '` (`' . $arr['Field'] . '`)';
				}
				elseif($arr['Key'] == 'MUL'){
					$table_index .= ',KEY `' . $arr['Field'] . '` (`' . $arr['Field'] . '`)';
				}
			}
		}
		$table_struct['table_index'] = $table_index;
		return $table_struct;
	}
	
	function admin_log($do,$mtype=1){
	    global $id;
        if(empty($id)){
            $id=0;
        }
        if($mtype==2){
            $adminname=$_SESSION['EZ_School']['name'];
        }else{
            $adminname=$_SESSION['EZ_Admin']['name'];
        }
		$data=array('mod'=>MOD,'admin_name'=>$adminname,'addtime'=>TIME,'ip'=>get_client_ip(),'do'=>$do,'oid'=>$id,'mtype'=>$mtype);
		$this->insert('adminlog',$data);
        
       
		if(rand(1,10)==1){
			$this->delete('adminlog','addtime<"'.(TIME-3600*24*60).'"');
		}
	}

	function workman_log($workmanid,$operateid,$gid=0){
        global $ezhand;
        
        if(empty($workmanid)){
            return;
        }
        $data=array(
        "workmanid"=>$workmanid,
        "ctime"=>time(),
        "username"=>$_SESSION['EZ_Admin']['name'],
        "userid"=>$_SESSION['EZ_Admin']['id'],
        "operateid"=>$operateid,
        "operater"=>$operatelist[$operateid],
        "gid"=>$gid
        );
        
        $id=$this->insert('workman_log',$data);
        return $id;
    }
	function msg_insert($data, $msgset_id=0, $msgset = ''){
        global $ezhand;
		$user=$this->select('member','email,mobile','id="'.$data['uid'].'"');
		if(!isset($data['email']) || $data['email']==''){
			$data['email']=$user['email'];
		}
		if(!isset($data['mobile']) || $data['mobile']=='' || $data['mobile']==0){
			$data['mobile']=$user['mobile'];
		}
		
		$send_web=0;
		$send_email=0;
		$send_sms=0;
        if($msgset_id>0 || !empty($msgset)){
			if($msgset_id>0){
				//$m=ez_get_cache('msgset');
				//$msgset=$m[$msgset_id];
                $msgset=$ezhand->select('msgset','*',"id=".$msgset_id);  
			}
		    
			$title= $msgset['title'];
			$web_content=$msgset['web'];
			$web_open=$msgset['web_open'];
			$sms_content=$msgset['sms'];
			$sms_open=$msgset['sms_open'];
			$email_content=$msgset['email'];
			$email_open=$msgset['email_open'];

			if($web_content!='' && $data['uid']>0 && $web_open==1){
				preg_match_all('/\{(.*?)\}/',$web_content,$arr);
        		foreach($arr[0] as $k=>$v){
	        		$web_content=str_replace($v,$data[$arr[1][$k]],$web_content);
        		}
				$send_web=1;
			}
			
			if($sms_content!='' && $data['mobile']!='' && $sms_open==1 && $this->webset['sms']['open']==1){
				preg_match_all('/\{(.*?)\}/',$sms_content,$arr);
        		foreach($arr[0] as $k=>$v){
	        		$sms_content=str_replace($v,$data[$arr[1][$k]],$sms_content);
        		}
				$send_sms=1;
			}
			
			if($email_open==1 && $data['email']!='' && $email_content!=''){
				preg_match_all('/\{(.*?)\}/',$email_content,$arr);
        		foreach($arr[0] as $k=>$v){
	        		$email_content=str_replace($v,$data[$arr[1][$k]],$email_content);
        		}
				$send_email=1;
			}
		}
		else{
		    $title=$data['title'];
			if($data['content']!=''){
				$web_content=$data['content'];
				$send_web=1;
			}
			if($user['mobile']!=''){
				$sms_content=$data['content'];
				$send_sms=1;
			}
			if($data['email']!=''){
				$email_content=$data['content'];
				$send_email=1;
			}
		}
		
		$re_status=array(0,0,0);
		
		if($send_web==1){
			$field_arr['addtime']=date('Y-m-d H:i:s');
			$field_arr['see']=0;
			$field_arr['senduser']=0;
			$field_arr['uid']=$data['uid'];
			$field_arr['title']=$title;
			$field_arr['content']=$web_content;
			$id=$this->insert('msg',$field_arr);
			if($id>0){
				$re_status[0]=1;
			}
		}

		//if($send_sms==1){
		//	$ddopen=fs('ddopen');
		//	$ddopen->sms_ini($this->webset['sms']['pwd']);
		//	$ddopen->sms_send($data['mobile'],$sms_content,$msgset_id);
		//	$re_status[1]=1;
		//}
		
		if($send_email==1){
			if($this->webset['smtp']['xingshi']==0){
				$a=array('email'=>$data['email'],'title'=>$title,'content'=>$email_content,'type'=>1);
				$this->cron($a,'insert');
			}
			else{
				mail_send($data['email'], $title, $email_content);
			}
			$re_status[2]=1;
		}
		
		return $web_content;
	}
	
	function replace($table, $field_arr, $alert = 0) {
		$field = "";
		$values = "";
		foreach ($field_arr as $k => $v) {
			$field = "`" . $k . "`," . $field;
			$values = "'" . $v . "'," . $values;
		}
		$field = substr($field, 0, strlen($field) - 1);
		$values = substr($values, 0, strlen($values) - 1);
		$sql = "replace into $this->TABLEPRE$table($field) values ($values);";
		$query = $this->query($sql);
		if ($alert == 0) {
			if ($query)
				return mysql_insert_id();
			else
				return $this->error();
		}
		elseif ($alert == 1) {
			echo $sql . "<br/>";
		}
		elseif ($alert == 2) {
			echo $sql;
			if ($query)
				return mysql_insert_id();
			else
				return $this->error();
		}
	}
	
	function left_join($table, $join, $sel_field, $where='1=1', $alert = 0) {
		$arr = array ();
		$sql = "select $sel_field from ".$this->TABLEPRE.$table." LEFT JOIN ".$this->TABLEPRE.$join." where $where ";
		if ($alert == 1) {
			echo $sql;
		}
		$query = $this->query($sql);
		if ($query!='') {
			while ($row = $this->fetch_array($query)) {
				$arr[] = $row;
			}
			$this->free_result($query);
		}
		return $arr;
	}
	
	function sel_one_arr_sql($table, $sel_field, $where, $alert = 0) {
		$arr = array ();
		if(strstr($table,',')!=''){
		    $table=str_replace(',',','.$this->TABLEPRE,$table);
		}
		$sql = "select $sel_field from ".$this->TABLEPRE.$table." where $where ";
		if ($alert == 1) {
			echo $sql;
		}
		$query = $this->query($sql);
		if ($query!='') {
			while ($row = $this->fetch_array($query)) {
				$arr[] = $row[$sel_field];
			}
			$this->free_result($query);
		}
		return $arr;
	}
	
	function sel_page_sql($table, $sel_field, $where, $frmnum ,$pagesize) {
		$arr = array ();
		if($frmnum>=1000){ //自己估算的临界点
		    $sql="select $sel_field From ".$this->TABLEPRE.$table." Where id >=(Select id From ".$this->TABLEPRE.$table." Order By id limit $frmnum,1) and ".$where." limit $pagesize";
		}
		else{
		    $sql = "select $sel_field from ".$this->TABLEPRE.$table." where $where limit $frmnum ,$pagesize";
		}
		$query = $this->query($sql);
		if ($query!='') {
			while ($row = $this->fetch_array($query)) {
				$arr[] = $row;
			}
			$this->free_result($query);
		}
		return $arr;
	}

	function count($table,$where='',$alert=0){
		if($where!=''){$where ='where '.$where;}
		if(strpos($table,',')!==false){
		    $table=str_replace(',',','.$this->TABLEPRE,$table);
		}
	    $sql='select count(1) as num from '.$this->TABLEPRE.$table." ".$where;
		if($alert==1){
		    echo $sql;
		}
	    $query = $this->query($sql);
	    $row=$this->fetch_array($query);
		$this->free_result($query);
	    return $row['num']?$row['num']:0;
    }
	
	function count_orther($table,$where='',$alert=0){
		if($where!=''){$where ='where '.$where;}
		if(strpos($table,',')!==false){
		    $table=str_replace(',',',',$table);
		}
	    $sql='select count(1) as num from '.$table." ".$where;
		if($alert==1){
		    echo $sql;
		}
	    $query = $this->query($sql);
	    $row=$this->fetch_array($query);
		$this->free_result($query);
	    return $row['num']?$row['num']:0;
    }
	
	function sum($table,$count_field,$where='1=1',$alert=0){
		if($where!=''){$where ='where '.$where;}
		if(strpos($table,',')!==false){
		    $table=str_replace(',',','.$this->TABLEPRE,$table);
		}
		$select_field='';
		if(strpos($count_field,',')!==false){
			$field_arr=explode(',',$count_field);
			foreach($field_arr as $k=>$v){
				$select_field.='sum(`'.$v.'`) as `'.$v.'`,';
			}
			$select_field=preg_replace('/,$/','',$select_field);
		}
		else{
			$select_field='sum('.$count_field.') as sum';
		}
	    $sql="select ".$select_field." from ".$this->TABLEPRE.$table." ".$where;
		if($alert==1){echo $sql.'<br/>';}
	    $query = $this->query($sql);
	    $row=$this->fetch_array($query);
		$this->free_result($query);
		if(count($row)==1){
			return $row['sum']?round($row['sum'],2):0;
		}
	    else{
			foreach($row as $k=>$v){
				$row[$k]=(float)$v;
			}
			return $row;
		}
		return 0;
    }
	
	function delete($table,$where,$alert=0){
	    $sql="delete from ".$this->TABLEPRE.$table." where $where";
		$query = $this->query($sql);
		if($alert==1){
		    echo $sql;
		}
		if($query!=''){return 1;}
		else{return mysql_error();}
	}
	
	function delete_id_in($ids,$table=MOD,$alert=0,$addwhere=""){
	    $where="id IN(".$ids.") ".$addwhere;
		$re=$this->delete($table,$where,$alert=0);
		return $re;
	}
	
	function creat_table($name) {
		
        $query=$this->query("show tables like '".$this->TABLEPRE.$name."'"); 
		$row=$this->fetch_array($query);
        if(!empty($row)){
          return false;      
        }
		//$sql = 'DROP TABLE IF EXISTS `' . $this->TABLEPRE . $name . '`;';
		//$this->query($sql);
		$sql = 'CREATE TABLE `' . $this->TABLEPRE . $name . '` (';
        $sql .= '`id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(200) NOT NULL,
  `tid` int(11) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
';
		$query=$this->query($sql);
        
		return $query;
	}
	
	function delete_table($table){
		$query=$this->query("show tables like '".$this->TABLEPRE.$table."'"); 
		$row=$this->fetch_array($query);
		if(!empty($row)){
		    $sql="DROP TABLE `".$this->TABLEPRE.$table."` ";
            
		    $query=$this->query($sql);
		}
		else{
		    return $this->error();
		}
	}
	
	function show_fields($table,$field=''){
		$query=$this->query('show fields from `'.$this->TABLEPRE.$table.'`;');
		$field_arr=array();
        while($arr=$this->fetch_array($query)){
		    $field_arr[]=$arr['Field'];
		}
		$this->free_result($query);
		if($field==''){
			return $field_arr;
		}
		else{
			if(in_array($field,$field_arr)){
				return 1;
			}
			else{
				return 0;
			}
		}
	}
	function rename_table($table1, $table2) {
		$sql = "ALTER TABLE `" . $this->TABLEPRE . $table1 . "` rename `" . $this->TABLEPRE . $table2 . "`;";
		$this->query($sql);
    }
	function reapaire_field($table, $field_name, $field_info) {
		$sql = "ALTER TABLE `" . $this->TABLEPRE . $table . "` add `" . $field_name . '` ' . $field_info . ";";
		$this->query($sql);
	}
	
function set_constants($table) {
	$data = array ();
	$sql = "show fields from " . $this->TABLEPRE . $table; //得到全表信息
	$query = $this->query($sql);
	while ($row = $this->fetch_array($query)) {
		$data[] = str_replace('_', '', strtoupper($row['Field']));
	}

	$data = array_diff($data, array ('ID'));

	$sql = "select * from " . $this->TABLEPRE .$table." where id=1";
	$query = $this->query($sql);
	$i = 1;
	$set = $this->fetch_array($query, MYSQL_NUM);

	for ($i = 1; $i < count($set); $i++) {
		define($data[$i], $set[$i]);
	}
	define('SITEURL', 'http://'.URL);
}

	

	function check_user($username){
		    $id=$this->select('member','id',"username='$username'");
		    if($id>0) return 'false';
		    else return 'true';
	}
	
	function check_nickname($nickname,$uid=""){
	   if(!empty($uid)){
		    $id=$this->select('member','id',"nickname='$nickname' and id<>".$uid);
      }else{
		    $id=$this->select('member','id',"nickname='$nickname'");
        
      }
		    if($id>0) return 'false';
		    else return 'true';
	}
        
	function check_oldpass($oldpass,$uid){

			$id=$this->select('member','id',"id='$uid' and password='".md5($oldpass)."'");
			if($id>0) return 'true';
			else return 'false';
    }
	
	function check_email($email,$uid=""){
            if(!empty($uid)){
                $id=$this->select('member','id',"email='$email' and id<>".$uid);
            }else{
                $id=$this->select('member','id',"email='$email'");    
            }
		    
		    if($id>0) return 'false';
		    else return 'true';
		
	}
	
	function check_mobile($mobileno,$uid=""){
	       if($uid<>""){
             $id=$this->select('member','id',"mobile='$mobileno' and id<>".$uid);
	       }else{
	         $id=$this->select('member','id',"mobile='$mobileno'");  
	       }
    	    if($id>0) return 'false';
		    else return 'true';
	}
        function check_cardno($cardno){
                $list=$this->select('cardlist','id',"cardno='$cardno'");
                return $list;
	}
  
	function check_alipay($alipay){
	    $id=$this->select('member','id',"alipay='$alipay'");
		if($id>0) return 'false';
		else return 'true';
	}
	
	function check_my_email($email,$dduserid){
	    $id=$this->select('member','id',"id<>'$dduserid' and email='".$email."'");
		if($id>0){
		    return $id;
		}
		else{
		    return 0;
		}
	}

	function check_my_field($f,$v,$dduserid){
	    $id=$this->select('member','id',"id<>'$dduserid' and ".$f."='".$v."'");
		if($id>0){
		    return $id;
		}
		else{
		    return 0;
		}
	}
	function set_mode_cache($tables,$field="id,title") {
	  
        $listrow=$this->select_all($tables,$field,'1=1');
        $list=array();
        while(list($k,$trow)=each($listrow)){
            $typeid=$trow["id"];
            $list[$typeid]=$trow;
        }
    
        ez_set_cache($tables,$list);
           
       
    }
    
	function webset($l=0) {
		$arr = $this->select_all('webset', '*', 'type>=0');
		if(empty($arr)){
			return false;
		}
		$webset = array ();
		foreach ($arr as $row) {
			if ($row['type'] == 1) {
				$row['val'] = unserialize($row['val']);
			} else {
				$row['val'] = $row['val'];
			}
			$webset[$row['var']] = $row['val'];
		}

		//$arr = $this->select_all('webset', '*', 'type=2');
		//if(empty($arr)){
		//	return false;
		//}
		foreach ($arr as $row) {
			if($row['id']<90){
				$name = str_replace('_', '', strtoupper($row['var']));
			}
			else{
				$name = strtoupper($row['var']);
			}
			
			$constant[$name]=$row['val'];
			if($l==200){
				define($name,$row['val']);
			}
		}
		if($l==200){
			return $webset;
		}
		ez_set_cache('webset',$webset);

		if($l==1){return;} //只更新webset就结束
	}
    function check_navmenu($nav){
         global $_SESSION;
         $role_id=$_SESSION['EZ_Admin']['role_id'];
        $count=$this->select('menu m,menu_access a','count(*) as c',"m.id=a.menu_id and a.role_id='$role_id' and m.topnav='$nav'");
       
        if(!empty($count["c"])){
            return true;
        }else{
            return false;
        }
       
        
        
    }
	
    function check_menu_access($mod,$act){
        global $_SESSION;
    
        $role_id=$_SESSION['EZ_Admin']['role_id'];
        $id=$this->select('menu m,menu_access a','a.id',"m.id=a.menu_id and a.role_id='$role_id' and m.mod='$mod' and m.act='$act'");
        if(!empty($id)){
            return $id;
        }else{
            return 0;
        }
    
    
    }
    

	function set_webset($var,$val,$jiance=1){
		if(preg_match('/[A-Z]{1,50}/',$var)){ //大写字母，是常量定义
			$type=2;
			$var=strtolower($var);
		}
		else{
			if(is_array($val)){
				$val=serialize($val);
				$type=1;
			}
			else{
				$type=0;
			}
		}
		
		if($jiance==1){
			$webset_field=$this->select_2_field('webset','id,var','1=1');
			$id=(int)array_search($var,$webset_field);
		}
		else{
			$id=1;
		}
		if($id>0){
			$data=array('val'=>$val,'type'=>$type);
			$this->update('webset',$data,'var="'.$var.'"');
		}
		else{
			$data=array('val'=>$val,'var'=>$var,'type'=>$type);
			$this->insert('webset',$data);
		}
	}
     function tpl_form_field_daterange($name, $value = array(), $options = array()) {
	$s = '';
	if (!defined('INCLUDE_DATERANGE')) {
		$s = '
		<link type="text/css" rel="stylesheet" href="/resource/style/daterangepicker.css" />
		<script type="text/javascript" src="/resource/script/daterangepicker.js"></script>';
	}
	if ($this->strexists($name, '[')) {
		$id = str_replace(array('[', ']'), '_', $name);
        //echo $id;
		$startname = $name . '[start]';
		$endname = $name . '[end]';
	} else {
		$startname = $name . '-start';
		$endname = $name . '-end';
	}
    $id=$name;
	define('INCLUDE_DATERANGE', true);
	$value['starttime'] = empty($value['starttime']) ? mktime(0, 0, 0) :  $value['starttime'];
	$value['endtime'] = empty($value['endtime']) ? ($value['starttime'] + 46800) :  $value['endtime'];
	$s .= '
	<input name="'.$startname.'" id="'.$id.'-start" type="hidden" value="'.date('Y-m-d', $value['starttime']).'" />
	<input name="'.$endname.'" id="'.$id.'-end" type="hidden" value="'.date('Y-m-d', $value['endtime']).'" />
	<button class="btn" id="'.$id.'-date-range" class="date" type="button"><span class="date-title">'.date('Y-m-d', $value['starttime']).' 至 '.date('Y-m-d', $value['endtime']).'</span> <i class="icon-caret-down"></i></button>
	<script type="text/javascript">
	var dateddd = $("#'.$id.'-date-range").daterangepicker({
		format: "YYYY-MM-DD",
		startDate: $(":hidden[id='.$id.'-start]").val(),
		endDate: $(":hidden[id='.$id.'-end]").val(),
		parentEl: $("#container"),
		locale: {
			applyLabel: "确定",
			cancelLabel: "取消",
			fromLabel: "从",
			toLabel: "至",
			weekLabel: "周",
			customRangeLabel: "日期范围",
			daysOfWeek: moment()._lang._weekdaysMin.slice(),
			monthNames: moment()._lang._monthsShort.slice(),
			firstDay: 0
		}
	}, function(start, end){
		$("#'.$id.'-date-range .date-title").html(start.format("YYYY-MM-DD") + " 至 " + end.format("YYYY-MM-DD"));
		$(":hidden[id='.$id.'-start]").val(start.format("YYYY-MM-DD"));
		$(":hidden[id='.$id.'-end]").val(end.format("YYYY-MM-DD"));
	});
    //dateddd.hide();
	</script>';
	return $s;
}
/**
 * 是否包含子串
 */

function strexists($string, $find) {
	return !(strpos($string, $find) === FALSE);
}	

}
?>